import { app, protocol } from "electron";
import { initTray } from "@/electron/rendererTray"; // 初始化系统托盘图标
import { createMainWindow, mainWindow } from '@/electron/mainWindow' // 创建主窗口

const isDevelopment = process.env.NODE_ENV !== "production";

protocol.registerSchemesAsPrivileged([
  { scheme: "app", privileges: { secure: true, standard: true } },
]);

const createWindow = async () => {
  
}
/**
 * requestSingleInstanceLock 此方法的返回值表示你的应用程序实例是否成功取得了锁。 如果它取得锁失败，你可以假设另一个应用实例已经取得了锁并且仍旧在运行，并立即退出。
 *
 * second-instance
 * */
const additionalData = { myKey: "myValue" };
const gotTheLock = app.requestSingleInstanceLock(additionalData); // return Boolean
console.log("gotTheLock", gotTheLock);
if (!gotTheLock) {
  app.quit();
} else {
  app.on(
    "second-instance",
    (event, commandLine, workingDirectory, additionalData) => {
      // 输出从第二个实例中接收到的数据
      console.log(additionalData);
      // 有人试图运行第二个实例，我们应该关注我们的窗口 将焦点聚焦到现有的窗口
      if (mainWindow) {
        if (mainWindow.isMinimized()) mainWindow.restore();
        mainWindow.focus();
      }
    }
  );
  app.whenReady().then(async () => {
    console.log('whenReady');
    createMainWindow(createWindow);
    initTray();
  });
}

if (isDevelopment) {
  if (process.platform === "win32") {
    process.on("message", (data) => {
      if (data === "graceful-exit") {
        app.quit();
      }
    });
  } else {
    process.on("SIGTERM", () => {
      app.quit();
    });
  }
}

/**
 * 生命周期
 *
 * ready 应用程序初始化完成
 *
 * browser-window-create 窗口创建完成
 *
 * beforre-quit 窗口关闭之前
 *
 * will-quit 窗口关闭了 但是程序还没关闭，即将关闭
 *
 * window-all-closed 全部窗口关闭
 * 
 * quit 应用程序关闭
 *
 */
app.on("ready", () => {
  console.log('ready');
});
app.on("browser-window-create", () => {
  console.log('browser-window-create');
});
app.on("beforre-quit", () => {
  console.log('beforre-quit');
});
app.on("window-all-closed", () => {
  console.log('process.platform', process.platform);
  if (process.platform !== "darwin") {
    app.quit();
  }
});
app.on("will-quit", () => {
  console.log('will-quit');
});
app.on("quit", () => {
  console.log('quit');
});
